package cn.wolfcode.producer2.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class TestController {

    @Autowired
    private RocketMQTemplate template;

    @RequestMapping("/test/{msg}")
    public String toTest(@PathVariable("msg") String msg){

        SendResult sendResult = template.syncSend("02-boot", msg);
        System.out.println(sendResult.getMsgId());

        return "发送消息 ok";
    }

    @RequestMapping("/async/{msg}")
    public String async(@PathVariable("msg") String msg){
        template.asyncSend("02-boot", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.err.println("发送失败");
            }
        });
        return "消息已发送";
    }

    @RequestMapping("/one")
    public String one(String msg){
        template.sendOneWay("02-boot",msg);
        return "消息发送 ok";
    }

    @RequestMapping("/delay")
    public String delay(String msg){
        MessageBuilder builder = MessageBuilder.withPayload(msg);
        Message<String> message = builder.build();

        SendResult sendResult = template.syncSend("02-boot", message, 3000, 3);
        System.out.println(sendResult.getMsgId());
        return "消息发送 ok";
    }

    @RequestMapping("/tag")
    public String tag(String msg,String tag){
        SendResult sendResult = template.syncSend("02-boot:" + tag, msg);
        System.out.println(sendResult.getMsgId());
        return "发送消息 ok";
    }

    @RequestMapping("/definedFileter")
    public String definedFileter(String msg,String key,String other){

        Map<String,Object> map = new HashMap<>();
        map.put("name","zhangfei");
        map.put("age","40");
        map.put("other",other);
        map.put(MessageConst.PROPERTY_KEYS,key);

        template.convertAndSend("02-boot",msg,map);

        return "消息发送 OK";
    }
}
